package com.fcl.blog.web;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.fcl.blog.comment.Result;
import com.fcl.blog.dto.BlogDto;
import com.fcl.blog.exception.ServiceException;
import com.fcl.blog.mapper.BlogMapper;
import com.fcl.blog.po.*;
import com.fcl.blog.service.BlogService;
import com.fcl.blog.service.TagService;
import com.fcl.blog.service.TypeService;
import com.fcl.blog.service.UserServie;
import com.fcl.blog.vo.BlogVo;
import com.fcl.blog.vo.Page;
import com.fcl.blog.vo.SearchVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author 付
 * @Date 2023/10/24 12:13
 * @Version 1.0
 * @description
 * @since 1.0
 */

@RestController
@RequestMapping("/admin")
@Slf4j
public class BlogController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;
    @Autowired
    private UserServie userServie;


    @GetMapping("/blogs")
    public Result getListBlogs(){
        Long total = blogService.blogAdminCount();
        PageHelper.startPage(1,new Page().getPagesize());
        List<Blog> blogs = blogService.selectListAdminBlog();

        List<BlogDto> blogDtos = new ArrayList<>();
        blogs.forEach(blog -> {
            BlogDto blogDto = new BlogDto();
            blogDto.setId(blog.getId());
            blogDto.setDate( DateUtil.formatDate(blog.getUpdateTime()));
            blogDto.setName(blog.getTitle());
            blogDto.setSuggestion(blog.isShareStatement()?"是":"否");
            blogDto.setType(String.valueOf(typeService.selectById(blog.getTypeId()).getName()));
            blogDto.setStatus(blog.isPublished()?"发布":"草稿");
            blogDtos.add(blogDto);
        });

        PageInfo<BlogDto> blogPageInfo = new PageInfo<>(blogDtos);
        blogPageInfo.setTotal(total);

        return Result.success(blogPageInfo);
    }

    @GetMapping("/pageBlog")
    public Result pageBlogs(@RequestParam("pageNum") String page){
        Long total = blogService.blogAdminCount();

        PageHelper.startPage(Integer.parseInt(page),new Page().getPagesize());
        List<Blog> listBlog = blogService.selectListAdminBlog();

        List<BlogDto> blogDtos = new ArrayList<>();
        listBlog.forEach(blog -> {
            BlogDto blogDto = new BlogDto();
            blogDto.setId(blog.getId());
            blogDto.setDate( DateUtil.formatDate(blog.getUpdateTime()));
            blogDto.setName(blog.getTitle());
            blogDto.setSuggestion(blog.isShareStatement()?"是":"否");
            blogDto.setType(String.valueOf(typeService.selectById(blog.getTypeId()).getName()));
            blogDto.setStatus(blog.isPublished()?"发布":"草稿");
            blogDtos.add(blogDto);
        });

        PageInfo<BlogDto> pageInfo = new PageInfo<>(blogDtos);

        pageInfo.setTotal(total);
        return Result.success(pageInfo);
    }


    // 添加博客
    @PostMapping("/addBlog")
    public Result addBlog(@RequestBody BlogVo blogVo, HttpServletRequest request) throws ServiceException {
        try {
            if (blogVo.getValue()==null || blogVo.getType()==null || blogVo.getName() == null){
                return Result.error("抱歉，内容、标题、分类不能为空");
            }
        }catch (Exception e){
            log.error("空指针"+e);
            throw new ServiceException("空指针异常");
        }

        Blog blog = new Blog();
        blog.setId(Math.abs(Long.valueOf(IdUtil.randomUUID().replaceAll("-","").hashCode())));
        blog.setFlag(blogVo.getFlag());
        blog.setTitle(blogVo.getName());
        blog.setContent(blogVo.getValue());
        blog.setTypeId(Long.valueOf(blogVo.getType()));
        blog.setRecommend(blogVo.isRecommend());
        blog.setPublished(blogVo.isPublished());
        blog.setCommentTabled(blogVo.isCommentTabled());
        blog.setCreateTime(new Date());
        blog.setFirstPicture(blogVo.getType());

        blog.setUserId("352275778");
        blog.setUpdateTime(new Date());
        blog.setShareStatement(blogVo.isShareStatement());

       List<BlogTags> list = new ArrayList<>();

        List<String> tags = blogVo.getTags();
        tags.forEach(tag ->{
            list.add(new BlogTags(null,blog.getId(),Long.valueOf(tag)));
        });
        int y=0;
        for (int i = 0; i <list.size() ; i++) {
            y += blogService.insertBlogTags(list.get(i));
        }
        try {
            int i = blogService.insertBlog(blog);

            if (i==0 || y != list.size()){
                log.error("添加失败--->"+(new Date()));
                return  Result.error("抱歉，添加失败！！");
            }
        }catch (Exception e){
            throw new ServiceException("抱歉，添加失败");
        }

        return Result.success("新增成功！");
    }


    // 搜索
    @PostMapping("/search")
    public Result searchBlog(@RequestBody SearchVo searchVo){
        if (searchVo==null){
            return Result.error("抱歉，您搜索的内容为空");
        }
        Long total = blogService.blogAdminCount();
        PageHelper.startPage(1,new Page().getPagesize());
        List<Blog> blogs = blogService.searchAdminBlog(searchVo.getTitle(), searchVo.getType());
        List<BlogDto> blogDtos = new ArrayList<>();
        blogs.forEach(blog -> {
            BlogDto blogDto = new BlogDto();
            blogDto.setId(blog.getId());
            System.out.println("blog.getUpdateTime() = " + blog.getUpdateTime());
            blogDto.setDate( DateUtil.formatDate(blog.getUpdateTime()));
            blogDto.setName(blog.getTitle());
            blogDto.setSuggestion(blog.isShareStatement()?"是":"否");
            blogDto.setType(String.valueOf(typeService.selectById(blog.getTypeId()).getName()));
            blogDto.setStatus(blog.isPublished()?"发布":"草稿");
            blogDtos.add(blogDto);
        });
        PageInfo<BlogDto> blogPageInfo = new PageInfo<>(blogDtos);
        blogPageInfo.setTotal(total);
        return Result.success(blogPageInfo);
    }

    @GetMapping("/delete")
    public Result deleteBlog(@RequestParam("id") String id){
        int i = blogService.deleteById(Long.valueOf(id));
        if (i==0){
            return Result.error("抱歉，删除失败");
        }
        return Result.success("删除成功");
    }
}
